package com.usefullc.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author: Sampson
 * @date: 2022-02-21 14:54
 */
public class SignUtils {


    private static  Logger logger = LoggerFactory.getLogger(SignUtils.class);

    public static String sign(Object param,String privateKey){
        //私钥签名
        String paramJson = JsonUtil.bean2Json(param);
        TreeMap<String,Object> treeMap = JsonUtil.json2Bean(paramJson, TreeMap.class);
        String content = treeMap.entrySet().stream().filter(data->data.getValue() != null && !data.getValue().toString().trim().equals(""))
                .map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        logger.info("sign before param={}",content);
        String sign = RSAUtils.sign(content.getBytes(), privateKey);
//        return content + "&sign="+sign;
        return sign;
    }

    public static boolean verify(Object param,String publicKey){
        //公钥验签
        String paramJson = JsonUtil.bean2Json(param);
        TreeMap<String,Object> treeMap = JsonUtil.json2Bean(paramJson, TreeMap.class);
        String sign = treeMap.get("sign").toString();
        treeMap.remove("sign");
        String content = treeMap.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        logger.info("sign before content={}",content);
        boolean status = RSAUtils.verify(content.getBytes(), publicKey, sign);
        return status;
    }

}
